<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- 搜索和添加区域 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="this.userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="角色" prop="mobile"></el-table-column>
        <el-table-column label="姓名" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <!-- 修改 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
            <!-- 分配角色  tooltip 是鼠标移动商上去时候 提示 文字内容  enterable 鼠标是否能进入到提示内容中-->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--  分页区-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改的对话框 -->
    <el-dialog title="修改用户" :visible.sync="dialogEdittVisible" width="50%" @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="editForm2" ref="editFormRef" :rules="editFormRules" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm2.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm2.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="moblie">
          <el-input v-model="editForm2.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEdittVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 设置用户的角色的对话框 -->
    <el-dialog title="设置角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleClosed">
      <!-- 内容主体区域 -->
      <div>
        <p>当前用户是：{{ userInfo.username }}</p>
        <p>当前角色是: {{ userInfo.role_name }}</p>
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
        </el-select>
      </div>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('邮箱格式有问题'))
    }

    var checkMobil = (rule, value, cb) => {
      const regMobile = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      roleList: [],
      total: 0,
      dialogVisible: false,
      // 修改用户框可视化
      dialogEdittVisible: false,
      // 添加用户的表单数据
      // 添加用户角色表单
      setRoleDialogVisible: false,
      addForm: {
        username: 'adminfff',
        password: '123456',
        email: '123@qq.com',
        mobile: '13831087564'
      },
      // 编辑用户 查询结果
      editForm2: {},
      // 验证用户数据是否合法的
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名和邮箱', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3-10个之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名的长度在6-15个之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobil, trigger: 'blur' }
        ]
      },
      // 校验编辑用户是否合法
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        moblie: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobil, trigger: 'blur' }
        ]
      },
      // 编辑用户角色的data
      userInfo: {},
      selectedRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败，请检查网络')
      }
      this.userList = res.data.users
      this.total = res.data.total
      //   console.log(res)
    },
    // 监听页面页码改变的事件
    handleSizeChange (newsize) {
      //   console.log('sizecha' + newsize)
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },
    // 监听页面数值改变的事件
    handleCurrentChange (newnumber) {
      //   console.log('current' + newsize)
      this.queryInfo.pagenum = newnumber
      this.getUserList()
    },
    // 监听switch开关的状态
    async userStateChanged (userinfo) {
      //   console.log(userinfo)
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('错误')
      }
      this.$message.success('成功')
    },
    // 监听添加对话框关闭后清空表单
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听编辑用户对话框关闭后清空表单
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 展示编辑用户的对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      this.editForm2 = res.data
      this.dialogEdittVisible = true
      // console.log(this.editForm2)
      // console.log(this.editForm2.mobile)
    },
    addUser () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('检验数据')
        // 发起添加用户的网络请求
        console.log(this.addFrom)
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        // 隐藏对话框
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 验证修改用户表单是否合法
    editUserInfo () {
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(this.editForm2.email + '' + this.editForm2.mobile)
        // if (!valid) return this.$message.error('表单不合法')
        // 合法
        const { data: res } = await this.$http.put('users/' + this.editForm2.id, { email: this.editForm2.email, mobile: this.editForm2.mobile })
        if (res.meta.status !== 200) return this.$message.error('错误请求')
        this.$message.success('成功')
        this.dialogEdittVisible = false
        this.getUserList()
      })
    },
    // 删除用户
    async removeUserById (id) {
      // 弹框 是否删除用户
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err) // 返回error消息
      // console.log(confirmResult)
      if (confirmResult !== 'comfirm') {
        return this.$message.info('取消')
      } else {
        const { data: res } = await this.$http.delete('users' + id)
        if (res.meta.status !== 200) {
          return this.$message.error('删除失败')
        } else {
          return this.$message.success('删除成功')
        }
        // console.log('确认删除')
      }
    },
    // 点击配置角色按钮后
    async setRole (userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色失败')
      }
      this.roleList = res.data

      this.setRoleDialogVisible = true
    },
    // 用户分配好角色点击确定
    async saveRoleInfo () {
      if (!this.selectedRoleId) { return this.$message.error('请选者角色') }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success('更新成功')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    setRoleClosed () {
      this.selectedRoleId = ''
      this.userinfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}
</style>
